import axios from "axios";
import { Message } from "element-ui";
import { getToken } from '@/utils/auth'
import { getTimeStamp } from './auth'
import store from '@/store'

const timelen = 2 * 1000 * 60 * 60
// const timelen = 2 * 1000 * 4
const checkTimeOut = () => {
  let nowTime = Date.now()
  let loginTime = getTimeStamp()
  return (nowTime - loginTime) >= timelen
}

const service = axios.create({
  baseURL: process.env.VUE_APP_ApiUrl,
  timeout: 50000
})
// 请求拦截器
service.interceptors.request.use(config => {
  const token = getToken()
  // if (token) config.headers.Authorization = `Bearer ${store.getters.token}`
  if (token) {
    // console.log(token);
    // 判断登录时间是否超过token的有效期
    if (checkTimeOut()) {
      console.log(checkTimeOut());
      Message.error('登录过期了，请重新登录')
      store.dispatch('user/quiOut')
      router.push('/login')
      return Promise.reject('token过期，登陆失效')

    }
    config.headers.Authorization = `Bearer ${token}`
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器
service.interceptors.response.use(response => {
  // console.log(response);
  // 服务器返回的内容
  return response.data
}, error => {
  console.dir(error);
  console.log(error);
  // token过期处理
  if (error.message == 'Request failed with status code 401' && error.static) {
    Message.error('登录过期了，请重新登录')
    store.dispatch('user/quiOut')
    router.push('/login')
  }
  return Promise.reject(error);
})

export default service
